<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;
use app\api\controller\KbxOrder;
use think\Db;
use app\api\controller\KbxToken as KbxToken;
use app\admin\model\City as CityModel;
class City extends User
{
    public function addcountry()
    {
        //获取国家id
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new CityModel();
        //是正常添加操作
        if($id > 0) {
            //是修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '中文名称不能为空'],
                    ['eng_name', 'require', '英文名称不能为空'],
                    ['code', 'require', '电话区号不能为空'],
                    ['abbreviation', 'require', '国际域名缩写不能为空'],
                    ['currency_code', 'require', '货币类型不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $continentList = $this->getContinentList();
                $this->assign('continentList',$continentList);
                $city = Db::name('city')->where('id',$id)->select();
                if(!empty($city)) {
                    $this->assign('menu',$city[0]);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        } else {
            //是新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '中文名称不能为空'],
                    ['eng_name', 'require', '英文名称不能为空'],
                    ['code', 'require', '电话区号不能为空'],
                    ['abbreviation', 'require', '国际域名缩写不能为空'],
                    ['currency_code', 'require', '货币类型不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                if(Db::name('city')->where('name',$post['name'])->select()) {
                    return $this->error('国家已存在');
                }
                //同步数据到订单系统
                $res = (new KbxOrder())->pushNewCountryToKbx($post);
                if(!empty($res['id'])){
                    $post['kbx_id'] = $res['id']??'';
                }
                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {

                    return $this->success('添加成功','admin/poi/index');
                }
            } else {
                //非提交操作
                $pid = $this->request->has('pid') ? $this->request->param('pid', null, 'intval') : null;
                if(!empty($pid)) {
                    $this->assign('pid',$pid);
                }
                $menu = $model->select();
                $menus = $model->city($menu);
                $this->assign('menus',$menus);
                $continentList = $this->getContinentList();
                $this->assign('continentList',$continentList);
                return $this->fetch();
            }
        }
    }

    public function addcity()
    {
        //获取城市id
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new CityModel();
        //是正常添加操作
        if($id > 0) {
            //是修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '中文名称不能为空'],
                    ['eng_name', 'require', '英文名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                if(!empty($post['groupid'])){
                    $country = db('city')->find($post['groupid']);
                    if(!empty($country['continentid'])){
                        //获取国家对应的洲级分类
                        $post['continentid'] = $country['continentid']??0;
                    }
                }
                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功', 'admin/menu/index');
                }
            } else {
                //非提交操作
                $city = Db::name('city')->where('id',$id)->select();
                $country = Db::name('city')->where('id',$city[0]['groupid'])->select();
                $categorytags = db("tag")->where(['tag_status'=>1,'tag_type'=>7])->select();
                $cateArr = [];
                if(!empty($city[0]['categorytagids'])){
                    $categorytagIds = explode(',',$city[0]['categorytagids']);
                    $cateArr = db("tag")->field("tag_id,tag_name")->where(['tag_id'=>['in',$categorytagIds]])->select();
                }
                $this->assign('categorytags',$categorytags);
                $this->assign('cateArr',$cateArr);
                $this->assign('categorytagsStr',$city[0]['categorytagids']);
                if(!empty($city)) {
                    $this->assign('menu',$city[0]);
                    $this->assign('groupid',$city[0]['groupid']);
                    $this->assign('thumb',explode(',',$city[0]['thumb']));
                    $this->assign('wxx_thumb',explode(',',$city[0]['wxx_thumb']));
                    $this->assign('country',$country[0]['name']);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        } else {
            //是新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '中文名称不能为空'],
                    ['eng_name', 'require', '英文名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                if(Db::name('city')->where('name',$post['name'])->select()) {
                    return $this->error('城市已存在');
                }
                if(!empty($post['groupid'])){
                    $country = db('city')->find($post['groupid']);
                    if(!empty($country['continentid'])){
                        //获取国家对应的洲级分类
                        $post['continentid'] = $country['continentid']??0;
                    }
                }

                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {
                    $id = db()->getLastInsID();
                    //同步信息到订单系统
                    $kbx_res = (new KbxOrder())->pushNewCityToKbx($post);
                    if(!empty($kbx_res['id'])){
                        db('city')->where('id',$id)->update(['kbx_id'=>$kbx_res['id']]);
                    }
                    return $this->success('添加成功','admin/poi/index');
                }
            } else {
                //非提交操作
                $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;
                $country = Db::name('city')->where('id',$groupid)->select();
                $categorytags = db("tag")->where(['tag_status'=>1,'tag_type'=>7])->select();
                $this->assign('categorytags',$categorytags);
                $this->assign('groupid',$groupid);
                $this->assign('country',$country[0]['name']);
                $this->assign('thumb','');
                $this->assign('wxx_thumb','');

                return $this->fetch();
            }
        }
    }
    public function delcity()
    {
        $model = new CityModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $deleted = $this->request->has('deleted') ? $this->request->param('deleted', 0, 'intval') : 0;
        $data['deleted'] = $deleted;
        if(empty($deleted)){
            $data['getgoods'] = 0;
        }
        $cityinfo = $model->find($id);
        if(!empty($cityinfo['groupid']) && $pcity = $model->find($cityinfo['groupid'])){
            if(!empty($pcity['deleted'])){
                return $this->error("请先启用国家,在启用城市");
            }
        }
        Db::startTrans(); //启动事务
        try {

            $model->save($data,['id'=>$id]);
            $model->where("groupid",$id)->update($data);

            unset($data['getgoods']);
            $citys= Db::name('city')->where('groupid',$id)->field('id')->select();
            if($citys){
                foreach ($citys as $key=>$value){
                    Db::name('poi')->where('groupid',$value['id'])->where('active_delete',0)->update($data);
                }
            }else{
                Db::name('poi')->where('groupid',$id)->where('active_delete',0)->update($data);
            }
            Db::commit(); //提交事务
            return $this->success('修改成功','admin/poi/index');
        } catch (\PDOException $e) {
            Db::rollback(); //回滚事务
            return $this->error('修改失败');
        }
    }

    public function recommend(){

      $post=  request()->post();
       if ( !empty($post)){
           $t='';
         $city=db('city')->where('id',$post['id'])->find();
         if (isset($post['popular'])){
               if ($post['popular']==1){
                   $shu= db('city')->where('groupid',$city['groupid'])->where('popular',1)->count();
                   if ($shu>=8){
                       $res['msg']='只能设置8个热门城市';
                       $res['code']=1;
                       return $res;
                   }
               }

               $t= db('city')->where('id',$post['id'])->update([
//                   'recommend'=>$post['recommend'],
                   'popular'=>$post['popular']
               ]);
         }

           if (isset($post['recommend'])) {
               if ($post['recommend'] == 1) {
                   $shu = db('city')->where('groupid', $city['groupid'])->where('recommend', 1)->count();
                   if ($shu >= 9) {
                       $res['msg'] = '每个国家只能推荐9个城市';
                       $res['code'] = 1;
                       return $res;
                   }
               }
                   $t = db('city')->where('id', $post['id'])->update([
                       'recommend' => $post['recommend'],
//                 'popular'=>$post['popular']
                   ]);
           }

           $res=[];

        if ($t==true){
            $res['msg']='操作成功';
            $res['code']=2;
           return $res;
        }else{
            $res['msg']='操作失败';
            $res['code']=1;
            return $res;
        }
       }
    }

    public function getgoods(){
        $post=  request()->post();
        if ( !empty($post)){
            $t='';
            $city=db('city')->where('id',$post['id'])->find();
            if(empty($city['destid']) && $post['getgoods']==1){
                $res['msg']='该城市未关联viator城市id，无法抓取。';
                $res['code']=1;
                return $res;
            }

            if (isset($post['getgoods'])){
                $t= db('city')->where('id',$post['id'])->update([
                    'getgoods'=>$post['getgoods']
                ]);
            }

            $res=[];

            if ($t==true){
                $res['msg']='操作成功';
                $res['code']=2;
                return $res;
            }else{
                $res['msg']='操作失败';
                $res['code']=1;
                return $res;
            }
        }
    }

    //设置   是否在wap商城展示
    public function setshow(){
        $post = request()->post();
        if ( !empty($post)){
            $t='';
            $city=db('city')->where('id',$post['id'])->find();
            if (isset($post['show'])){
                $t= db('city')->where('id',$post['id'])->update([
                    'show'=>$post['show']
                ]);
            }
            $res=[];
            if ($t==true){
                $res['msg']='操作成功';
                $res['code']=2;
                return $res;
            }else{
                $res['msg']='操作失败';
                $res['code']=1;
                return $res;
            }
        }
    }

    //设置城市是否在小程序展示
    public function wxx_recommend(){
        $post = request()->post();
        if(!empty($post)){
            $t='';
            $city=db('city')->where('id',$post['id'])->find();
            if (isset($post['show'])){
                $t= db('city')->where('id',$post['id'])->update([
                    'wxx_recommend'=>$post['show']
                ]);
            }
            $res=[];
            if ($t==true){
                $res['msg']='操作成功';
                $res['code']=2;
                return $res;
            }else{
                $res['msg']='操作失败';
                $res['code']=1;
                return $res;
            }
        }
    }


    //城市关联订单系统城市ID
    public function kbxcity()
    {
        $post = $this->request->post();
        //获取订单系统的城市集
        $KbxToken = new KbxToken();
        $url=$KbxToken->url.'/client/cities';
        $token='Bearer '.$KbxToken->kbxToken();
        $city=$KbxToken->get_data($url,$token);
        $city=$KbxToken->object_array($city);

        if (isset($post['cityname']) and !empty($post['cityname'])) {
            foreach ($city as $k=>$v) {
                if($v['nameen']==$post['cityname']){
                    $city = array($v);
                }
            }
        }

        $this->assign('city',$city);
        return $this->fetch();
    }



    //脚本执行   关联订单系统的城市ID
    public function kbx_id(){
        //获取订单系统的城市集
        $KbxToken = new KbxToken();
        $url=$KbxToken->url.'/client/cities';
        $token='Bearer '.$KbxToken->kbxToken();
        $city=$KbxToken->get_data($url,$token);
        $city=$KbxToken->object_array($city);

        $my_city_arr = db('city')->field("id,name,eng_name,kbx_id")->select();
        $my_city = array();
        foreach ($my_city_arr as $k=>$v) {
            $enname = $v['eng_name'];
            $len = strlen($enname);
            $pot = substr($enname, $len-1, $len);
            if($pot=="."){
                $enname = substr($enname,0,-1);
            }
            $my_city[$enname] = $v;
        }

        $err_arr = array();
        foreach ($city as $k=>$v) {
            if(isset($my_city[$v['nameen']])){
                $kbx_id = $v['id'];
                $id = $my_city[$v['nameen']]['id'];
                if($kbx_id==$my_city[$v['nameen']]['kbx_id']){
                    echo "【".$id."已存在".$kbx_id."】：".$v['nameen']."<br>";
                }else{
                    $t= db('city')->where('id',$id)->update([
                        'kbx_id'=>$kbx_id
                    ]);
                    if($t){
                        echo "【".$id."保存成功】：".$v['nameen']."<br>";
                    }else{
                        echo "【!!!!!!!!!!!!!!!!!!!!!!!".$id."保存出错】：".$v['nameen']."<br>";
                    }
                }
            }else{
                $err_arr[] = "【未匹配到】：".$v['nameen'];
            }
        }

        echo "<br>****************************************************<br>";

        foreach ($err_arr as $v) {
            echo "<pre>";
            var_dump($v);
            echo "</pre>";
        }



    }


    //获取洲级分类
    public function getContinentList()
    {
        return db('continent')->field('id,name,eng_name')->order('sort asc')->select();
    }

    //获取城市的归属国家信息
    public function getCountryByCityId($city_id)
    {
        if(empty($city_id)) return $this->error('请选择城市！');
        $city = db('city')->find($city_id);
        $country = new \ArrayObject();
        if(!empty($city['groupid'])){
            $country = db('city')->find($city['groupid']);
        }
        return $this->success('success','',$country);
    }

}
